<?php


namespace app\api\controller;


use app\admin\model\RentalOrder;
use app\common\controller\Api;
use app\common\model\CarRepertoryCalendar;
use think\Db;
use think\Exception;

/**
 * 出租订单相关接口
 * Class RentalOrder
 * @package app\api\controller
 */
class Order extends Api
{
    // 订单列表需要登录才能访问
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 提交订单
     */
    public function submitOrder()
    {
        // 保存订单表
        $carId = $this->request->request('carId');
        $startDate = $this->request->request('startDate');
        $endDate = $this->request->request('endDate');
        $rentalOrder = new RentalOrder();
        $cars = new \app\admin\model\Cars();
        $price = $cars->where(['id' => $carId])->value('price');

        $data['cars_id'] = $carId;
        $data['user_id'] = $this->auth->id;
        $data['price'] = $price;
        $data['startdate'] = $startDate;
        $data['enddate'] = $endDate;
        $data['rental_day'] = $rentalOrder->getIntervalDay($startDate, $endDate);
        $data['status'] = 'ordering';
        // 启动事务
        Db::startTrans();
        try {
            $rentalOrder->save($data);
            // 车辆库存日历 库存减1
            $rentalOrder->reduceCarRepertory($carId, $startDate, $endDate);
            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('操作失败', $e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        // 更新订单状态为已取消
        $orderId = $this->request->request('orderId');
        $rentalOrder = new RentalOrder();
        $order = $rentalOrder->where('id',$orderId)->find()->toArray();
        $carId = $order['cars_id'];
        $startDate = $order['startdate'];
        $endDate = $order['enddate'];
        if($order['status']=='cancel'){
            $this->error('订单已取消，不用重复操作');
        }

        // 启动事务
        Db::startTrans();
        try {
            $saveSuc = $rentalOrder->isUpdate(true)->save(['id' => $orderId, 'status' => 'cancel']);
            $rentalOrder->addCarRepertory($carId,$startDate,$endDate);
            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('操作失败', $e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        // 订单类型
        $orderType = $this->request->request('orderType');
        //当前页
        $page = $this->request->param('page',1);
        //显示多少条数据
        $rows = $this->request->param('rows',5);
        // 订单类型枚举
        $typeEnum = ['ordering','renting','complete','cancel'];
        if(!array_key_exists($orderType,$typeEnum)){
            $this->error('订单类型不存在');
        }
        $where = " status = '$typeEnum[$orderType]' and user_id = {$this->auth->id}";
        $rentalOrder = new RentalOrder();
        $orderList = $rentalOrder->field('id,cars_id,user_id,price,startdate,enddate,rental_day,status')
            ->where($where)->page($page,$rows)->order('updatetime','desc')->select();

        $items = [];
        foreach ($orderList as $k=>$v){
            $car = $this->getCarInfo($v->cars_id);
            $items[$k]['id'] = $v->id;
            $items[$k]['deal'] = $v->status_text;
            // 得到车辆图片
            $server_url = "http://" . $_SERVER['HTTP_HOST'];
            $_arr = explode(',', $car->images);
            $items[$k]['goodsUrl'] = $server_url . $_arr[0];
            $items[$k]['title'] = $car->title;
            // 得到车辆短信息
            $info_arr = array_values(json_decode($car->json,true));
            $info_str = implode('/',$info_arr);
            $items[$k]['type'] = $info_str;
            $items[$k]['deliveryTime'] = '从'.$v->startdate.'到'.$v->enddate;
            $items[$k]['price'] = $v->price;
            $items[$k]['number'] = $v->rental_day;
        }

        $total = $rentalOrder->where($where)->count();
//        // 总页码
        $totalPage = ceil($total/$rows);
        $data = [
            'total' =>$total,
            'totalPage' => $totalPage,
            'items' => $items
        ];
        $this->success('操作成功',$data);
    }

    /**
     * 查询车辆详情
     * @param $carId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getCarInfo($carId){
        $cars = new \app\admin\model\Cars();
        return $cars->field('id,title,price,json,images')
            ->where(['id' => $carId])->find();
    }
}
